package com.onlocation.observers;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import com.onlocation.util.Logger;

/**
 * Author: Steve Carrell
 * Date: 5/22/12
 */
public abstract class AbstractCustomContentObserver extends ContentObserver {
    public static final int UPDATE_NEVER = -1;
    public static final int UPDATE_ON_LOC_CHANGE = 0;

    private Context context = null;
    private int missedNotifications = 0;

    AbstractCustomContentObserver(Context context) {
        super(null);
        this.context = context;
        updateMissedNotificationCount();
    }

    public abstract String getClassName();

    public abstract Uri getContentUri();

    public String getSelection() {
        return null;
    }
    
    public String[] getSelectionArgs() {
        return null;
    }

    public String[] getProjection() {
        return null;
    }

    @Override
    public void onChange(boolean selfChange) {
        updateMissedNotificationCount();
    }

    private void updateMissedNotificationCount() {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(
                    getContentUri(), getProjection(), getSelection(), getSelectionArgs(), null);

            missedNotifications = cursor.getCount();
        } catch (Exception e) {
            Logger.e(e.toString(), getClassName());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    
    public boolean hasMissedNotification() {
        return missedNotifications > 0;
    }
}
